var calendar = {
    dates : function(obj){
        if (!obj.id || !document.getElementById(obj.id)) {return false;}
        obj.dateArr = obj.dateArr || [];
        obj.callback = obj.callback || function(){};
        // 设置calendar div中的html部分
        this.renderHtml(obj);
        // 表格中显示日期
        this.showCalendarData(obj);
        //选中天
        this.selectEveDay(obj);
        // 绑定事件
        this.bindEvent(obj);
        //回调函数
        this.callbackEvent = obj.callback;
    },
    /**
     * 用于记录日期，显示的时候，根据dateObj中的日期的年月显示
     */
    dateObj : (function(){
        var _date = new Date();    // 默认为当前系统时间
        return {
            getDate : function(){
                return _date;
            },
            setDate : function(date) {
                _date = date;
            }
        };
    })(),
    /**
     * 日期转化为字符串， 4位年+2位月+2位日
     */
    getDateStr : function (date) {
        var _year = date.getFullYear();
        var _month = date.getMonth() + 1;    // 月从0开始计数
        var _d = date.getDate();

        _month = (_month > 9) ? ("" + _month) : ("0" + _month);
        _d = (_d > 9) ? ("" + _d) : ("0" + _d);
        return _year + _month + _d;
    },
    /**
     * 事件绑定
     */
    addEvent : function (dom, eType, func) {
        if(dom.addEventListener) {  // DOM 2.0
            dom.addEventListener(eType, function(e){
                func(e);
            });
        } else if(dom.attachEvent){  // IE5+
            dom.attachEvent('on' + eType, function(e){
                func(e);
            });
        } else {  // DOM 0
            dom['on' + eType] = function(e) {
                func(e);
            }
        }
    },
    callbackEvent : function(obj){
        var data = {};
        obj.callback(data);
        return data;
    },
    /**
     * 渲染html结构
     */
    renderHtml : function (obj) {
        var calendar = document.getElementById(obj.id);
        calendar.innerHTML = "";

        var dateBox = document.createElement("div");  // 日期
        var timeBox = document.createElement("div");  // 小时
        var titleBox = document.createElement("div");  // 标题盒子 设置上一月 标题
        var bodyBox = document.createElement("div");  // 表格区 显示数据
        var footerBox = document.createElement("div");  // 下一月

        dateBox.className = "date-box";
        calendar.appendChild(dateBox);

        // 设置标题盒子中的html
        titleBox.className = 'calendar-title-box';
        titleBox.innerHTML = "<span class='prev-month' id='prevMonth'></span>";
        dateBox.appendChild(titleBox);    // 添加到calendar div中

        // 设置表格区的html结构
        bodyBox.className = 'calendar-body-box';
        var _bodyHtml = "";
        // 一个月最多31天，所以一个月最多占6行表格 一个星期7天
        for(var i = 0; i < 42; i++) {
            _bodyHtml += "<tr>" + "<td></td>" + "</tr>";
        }
        bodyBox.innerHTML = "<table id='calendarTable' class='calendar-table'>" +  _bodyHtml + "</table>";
        // 添加到calendar div中
        dateBox.appendChild(bodyBox);
        // 设置标题盒子中的html
        footerBox.className = 'calendar-title-box';
        footerBox.innerHTML = "<span id='nextMonth' class='next-month'></span>";
        // 添加到calendar div中
        dateBox.appendChild(footerBox);

        timeBox.className = "time-box";
        var timeHead = "",timeBody = "",timeFoot = "",timeTable = "";
        timeHead += "<thead><tr class='calendar-title-box'>"
                  + "<th>时间</th>"
                  + "<th>预约</th>"
                  + "<th>已到</th>"
                  + "<th>已订</th>"
                  + "</tr></thead>";
        timeBody += "<tbody></tbody>";
        timeFoot += "<tfoot><tr class='calendar-title-box'><td colspan='4'></td></tr></tfoot>";
        timeTable += "<table id='timeTable' class='time-table'>" + timeHead + timeBody + timeFoot + "</table>";
        timeBox.innerHTML = timeTable;

        calendar.appendChild(timeBox);
        //calendar.innerHTML = dateBox + timeBox;
    },
    /**
     * 表格中显示数据，并设置类名
     */
    showCalendarData : function (obj) {
        var thisInstance = this;
        var _year = thisInstance.dateObj.getDate().getFullYear();
        var _month = thisInstance.dateObj.getDate().getMonth() + 1;
        var _dateStr = thisInstance.getDateStr(thisInstance.dateObj.getDate());
        //console.log(_dateStr);

        // 设置顶部标题栏中的 年、月信息
        var calendarTitle = document.getElementById("calendarTitle");
        var titleStr = _dateStr.substr(0, 4) + "年" + _dateStr.substr(4,2) + "月";
        //calendarTitle.innerText = titleStr;

        // 设置表格中的日期数据
        var _table = document.getElementById("calendarTable");
        var _tds = _table.getElementsByTagName("td");
        var _firstDay = new Date(_year, _month - 1, 1);  // 当前月第一天
        var choose = "";
        if(obj.dateArr.length > 0) {
            choose = '<span class="appoint"></span><span class="arrived"></span><span class="order"></span>';
        }
        for(var i = 0; i < _tds.length; i++) {
            var _thisDay = new Date(_year, _month - 1, i + 1 - _firstDay.getDay());
            var _thisDayStr = thisInstance.getDateStr(_thisDay);
            _tds[i].innerHTML = "<div class='date-holder'><span class='date'>" + _dateStr.substr(4,2) + "月" + _thisDay.getDate() + "日</span>" + choose + " </div>";
            _tds[i].setAttribute('data', _thisDayStr);
            if(_thisDayStr == thisInstance.getDateStr(new Date())) {    // 当前天
                _tds[i].className = 'currentDay';
                _tds[i].getElementsByClassName("date-holder")[0].classList.add("have-events");
            }else if(_thisDayStr.substr(0, 6) == thisInstance.getDateStr(_firstDay).substr(0, 6)) {
                _tds[i].className = 'currentMonth';  // 当前月
            }else {    // 其他月
                _tds[i].innerHTML = "";
                _tds[i].className = 'otherMonth';
            }
        }
    },
    /**
     * 绑定上个月下个月事件
     */
    bindEvent : function (obj) {
        var thisInstance = this;
        var prevMonth = document.getElementById("prevMonth");
        var nextMonth = document.getElementById("nextMonth");
        thisInstance.addEvent(prevMonth, 'click', function () {
            var date = thisInstance.dateObj.getDate();
            thisInstance.dateObj.setDate(new Date(date.getFullYear(), date.getMonth() - 1, 1));
            var _dateStr =thisInstance.getDateStr(thisInstance.dateObj.getDate()).substr(0, 6); //当前月
            var data = {};
            data.date = _dateStr;
            thisInstance.showCalendarData(obj);
            thisInstance.selectEveDay(obj);
            thisInstance.callbackEvent(data);
        });
        thisInstance.addEvent(nextMonth, 'click', function () {
            var date = thisInstance.dateObj.getDate();
            thisInstance.dateObj.setDate(new Date(date.getFullYear(), date.getMonth() + 1, 1));
            var _dateStr =thisInstance.getDateStr(thisInstance.dateObj.getDate()).substr(0, 6); //当前月
            var data = {};
            data.date = _dateStr;
            thisInstance.showCalendarData(obj);
            thisInstance.selectEveDay(obj);
            thisInstance.callbackEvent(data);
        });
    },
    /**
     * 查找指定父元素
     */
    patents:"",
    patent:function(elem,sel){
        var thisInstance = this;
        if(elem.parentNode.nodeName == sel.toUpperCase()){
            thisInstance.patents = elem.parentNode;
        }else{
            thisInstance.patent(elem.parentNode,sel);
        }
    },
    /**
     * 选择事件天
     */
    selectEveDay : function (obj){
        var thisInstance = this;
        if(obj.dateArr.length <= 0) {return false;}
        var table = document.getElementById("calendarTable");
        var tds = table.getElementsByTagName("td");
        var dateHolder = "";
        for(var a = 0;a < tds.length;a++){
            var date = tds[a].getAttribute("data");
            for (var b = 0; b < obj.dateArr.length; b++) {
                var _data = obj.dateArr[b];
                var _date = _data["date"]; // 传进来的日期
                var _appoint = _data["appoint"];
                var _arrived = _data["arrived"];
                var _order = _data["order"];
                if (date == _date) {
                    dateHolder = tds[a].getElementsByTagName("div")[0];
                    if (!dateHolder) {return false;}
                    dateHolder.getElementsByClassName("appoint")[0].innerHTML = _appoint;
                    dateHolder.getElementsByClassName("arrived")[0].innerHTML = _arrived;
                    dateHolder.getElementsByClassName("order")[0].innerHTML = _order;
                }
            }
            thisInstance.addEvent(tds[a], 'click', function (e) {
                window.e ? window.e.cancelBubble = true : e.stopPropagation();
                thisInstance.patent(e.target,"td");
                var td = thisInstance.patents;
                var date = td.getAttribute("data");
                for(var i = 0;i < tds.length;i++){
                    if(tds[i].childNodes.length >= 1){
                        tds[i].firstChild.classList.remove("have-events");
                    }
                }
                td.firstChild.classList.add("have-events");
                var data = {};
                data.td = td;
                data.date = date;
                thisInstance.callbackEvent(data);
            });
        }
    }
};
